package com.gexiaobao.pigeon.ui.fragment.mine.organization.activity

import android.annotation.SuppressLint
import android.graphics.Paint
import android.os.Bundle
import androidx.activity.OnBackPressedCallback
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import com.bin.david.form.core.SmartTable
import com.bin.david.form.data.style.FontStyle
import com.bin.david.form.data.style.LineStyle
import com.bin.david.form.data.table.MapTableData
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.model.bean.GroupTypeResponse
import com.gexiaobao.pigeon.app.model.param.SaveGroupParam
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.databinding.ActivityGroupNowBinding
import com.gexiaobao.pigeon.ui.dialog.RxDialogDefault
import com.gexiaobao.pigeon.viewmodel.OrgRaceViewModel
import com.google.gson.Gson
import com.lxj.xpopup.XPopup
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.LogUtils
import me.hgj.jetpackmvvm.util.startActivity
import org.json.JSONArray
import org.json.JSONObject


/**
 * @Author      : hxw
 * @Date        : 2024/6/26 17:59
 * @Describe    : 立即分组
 */
class ActivityGroupNow : BaseActivity<OrgRaceViewModel, ActivityGroupNowBinding>() {

    private lateinit var projectN: JSONObject
    private lateinit var tBody: JSONArray
    private lateinit var tHead: JSONArray
    private var orgIcon: String = ""
    private var raceName: String = ""
    private var orgName: String = ""
    private var mRuleFile = ""
    private var baseId = 0
    private var memberId = 0
    private var mRaceId = 0
    lateinit var data: SmartTable<Any>
    private var isEdit = false
    private var isEmptyData = false
    private var isEditGroup = false

    private lateinit var saveGroupParam: SaveGroupParam
    private var saveTeamItem: MutableList<SaveGroupParam.SaveTeamItem> = arrayListOf()

    @SuppressLint("SetTextI18n")
    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.setTranslucentForImageView(this, 0, null)
        mDatabind.includeBar.tvTitle.text = getString(R.string.Immediate_grouping)
        mDatabind.includeBar.tvRightMenu.isVisible = true
        mDatabind.includeBar.tvRightMenu.text = getString(R.string.fly_account_fragment_fly_detail_map_re)
        mDatabind.tvSignPeopleSearch.paint.flags = Paint.UNDERLINE_TEXT_FLAG
        mDatabind.tvGroupProcedure.paint.flags = Paint.UNDERLINE_TEXT_FLAG

        orgName = intent.getStringExtra("orgName").toString()
        raceName = intent.getStringExtra("raceName").toString()
        orgIcon = intent.getStringExtra("orgIcon").toString()
        baseId = intent.getIntExtra("baseId", 0)
        memberId = intent.getIntExtra("memberId", 0)
        mRaceId = intent.getIntExtra("raceId", 0)
        mDatabind.tvGroupOrgName.text = "$orgName$raceName"
        initSmartTable()

        showLoading(getString(R.string.loading))
        mViewModel.getAppMemberTeam(mRaceId.toString(), memberId)

        //监听系统返回键
        this.onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                if (isEdit) {
                    showBackDialog()
                } else {
                    finish()
                }
            }
        })
    }

    private fun initSmartTable() {
        data = mDatabind.smartTable as SmartTable<Any>
        val fontStyle = FontStyle(this, 16, ContextCompat.getColor(this, R.color.black))
        val contentStyle = FontStyle(this, 15, ContextCompat.getColor(this, R.color.comm_text_gray_dark))
        val lineStyle = LineStyle()
        lineStyle.color = ContextCompat.getColor(this, R.color.color_99CCFF)
        data.config.columnTitleStyle = fontStyle
        data.config.contentStyle = contentStyle
        data.config.setColumnTitleGridStyle(lineStyle)
        data.config.setContentGridStyle(lineStyle)
        data.config.setHorizontalPadding(20)
            .setVerticalPadding(15)
            .setColumnTitleVerticalPadding(20)
            .setSequenceHorizontalPadding(20)
            .setSequenceVerticalPadding(20)
            .setShowTableTitle(false) // 去除标题
            .setShowXSequence(false)
            .setShowYSequence(false)
            .isFixedYSequence = true
    }

    @SuppressLint("SetTextI18n")
    override fun createObserver() {
        super.createObserver()
        mViewModel.saveTeamResult.observe(this) {
            RxToast.showToast(getString(R.string.save_Successfull))
            finish()
        }
        /** 可报名的赛鸽列表  */
        mViewModel.memberTeamResult.observe(this) {
            if (it != null) {
                val data = Gson().toJson(it)
                val result = JSONObject(data.toString())
                if (result.has("dynamicTable")) {
                    val dynamicTableBody = result.getJSONObject("dynamicTable")
                    tHead = dynamicTableBody.getJSONArray("tHead")
                    tBody = dynamicTableBody.getJSONArray("tBody")
                    if (tBody.length() != 0 && tHead.length() != 0) {
                        isEmptyData = false
                        setSmartTableData()
                        showEmptyView(false)
                    } else {
                        isEmptyData = true
                        showEmptyView(true)
                    }
                } else {
                    isEmptyData = true
                    showEmptyView(true)
                    mDatabind.tvSaveGroup.isVisible = false
                }
                if (result.has("projectN")) {
                    projectN = result.getJSONObject("projectN")
                }

                baseId = result.getInt("baseId")
                mRuleFile = result.getString("ruleFile")
                mDatabind.tvDes.text = result.getString("des")
                mDatabind.tvNowGroupEndDate.text = getString(R.string.date_closed) + ": " + result.getString("endTime")
            }
        }
    }

    private fun showEmptyView(isEmpty: Boolean) {
        mDatabind.includeEmptyView.llEmptyData.isVisible = isEmpty
        mDatabind.smartTable.isVisible = !isEmpty
    }

    private fun setSmartTableData() {
        val list1 = ArrayList<Any>()
        var value: String
        for (i in 0 until tBody.length()) {
            val map = LinkedHashMap<String, String>()
            for (j in 0 until tHead.length()) {
                val dataHead = tHead[j].toString()
                val dataBody = tBody[i].toString()
                val key = JSONObject(dataHead).getString("hName")
                val valueStr = JSONObject(dataHead).getString("hKey")

                value = JSONObject(dataBody).getString(valueStr)
                when (valueStr) {
                    "ringId" -> value = Util.check2FormatRingId(value)
                }
                map[key] = value
            }
            list1.add(map)
        }
        val mapData = MapTableData.create(getString(R.string.Group_grouping), list1)
        mapData.columns[0].isFixed = true
        mapData.columns[1].isFixed = true
        mDatabind.smartTable.tableData = mapData

        data.tableData?.setOnItemClickListener { column, _, _, col, row ->//col-列，row-行：（下标从0开始）
            val nName: ArrayList<String> = arrayListOf()//储存可选的组名（a、b、c、d）
            val groupType = JSONObject(tHead.get(col).toString())//获取当前点击的这一列的head中的值
            val groupHeadKey = groupType.getString("hKey")//取出其中的value，作为projectN中的key
            if (projectN.has(groupHeadKey) && isEditGroup) {
                val result = projectN.getJSONObject(groupHeadKey).toString()
                val bean = Gson().fromJson(result, GroupTypeResponse::class.java)
                bean.codes.forEach {
                    nName.add(it.nName)
                }
                /** 使用 groupingBy 和 eachCount 统计每个元素的重复次数 */
                val countMap = column.datas.groupingBy { it }.eachCount()
                countMap.forEach {
                    if (it.value == bean.n) {
                        nName.remove(it.key)
                    }
                }
                showGroupDialog(nName, row, groupHeadKey)
            }
        }
    }

    private fun showGroupDialog(list: MutableList<String>, row: Int, groupHeadKey: String) {//col-列，row-行：（下标从0开始）
        list.add(0, "取消分组")
        XPopup.Builder(this) //.maxWidth(600)
            .maxHeight(800)
            .isDarkTheme(false)
            .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
            .asCenterList(getString(R.string.Please_select_a_group), list.toTypedArray()) { position, text ->
                isEdit = true
                refreshDataTBody(position, text, row, groupHeadKey)
            }.show()
    }

    private fun refreshDataTBody(position: Int, text: String, row: Int, groupHeadKey: String) {//col-列，row-行：（下标从0开始）
        val tvName = if (position == 0) {
            ""
        } else {
            text
        }
        val data = tBody.getJSONObject(row) // 获取索引为当前点击行的值
        data.put(groupHeadKey, tvName)
        setSmartTableData()
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.includeBar.ivBack,
            mDatabind.includeBar.tvRightMenu,
            mDatabind.tvSaveGroup,
            mDatabind.tvSignPeopleSearch,
            mDatabind.tvGroupProcedure,
            mDatabind.tvEditSignGroup
        ) {
            when (it) {
                mDatabind.tvEditSignGroup -> {
                    isEditGroup = true
                    mDatabind.tvSaveGroup.isEnabled = true
                    mDatabind.tvSaveGroup.setTextColor(ContextCompat.getColor(this, R.color.white))
                    mDatabind.tvSaveGroup.setBackgroundResource(R.drawable.round_btn_5a5a5a_5radiu_bg)
                }
                //团体规程
                mDatabind.tvGroupProcedure -> startActivity<ActivityGroupProcedure>(
                    "rule" to mRuleFile,
                    "title" to getString(R.string.Group_procedure)
                )

                mDatabind.tvSignPeopleSearch -> startActivity<ActivityGroupNowAllPerson>("raceId" to mRaceId)
                mDatabind.tvSaveGroup -> saveDataToRequest()
                mDatabind.includeBar.tvRightMenu -> {
                    /** 判断数据是否为空，为空直接刷新，不为空则弹窗提示后刷新 */
                    if (isEmptyData) {
                        showLoading(getString(R.string.loading))
                        mViewModel.getAppMemberTeam(mRaceId.toString(), memberId)
                    } else {
                        showDialog()
                    }
                }

                mDatabind.includeBar.ivBack -> {
                    if (isEdit) {
                        showBackDialog()
                    } else {
                        finish()
                    }
                }
            }
        }
    }

    private fun showBackDialog() {
        val dialog = RxDialogDefault(this)
        dialog.setTitle("")
        dialog.setContent(getString(R.string.is_exit_and_save_data))
        dialog.setSureListener {
            finish()
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun showDialog() {
        val dialog = RxDialogDefault(this)
        dialog.setTitle("")
        dialog.setContent(getString(R.string.is_refresh_and_save_data))
        dialog.setSureListener {
            showLoading(getString(R.string.loading))
            mViewModel.getAppMemberTeam(mRaceId.toString(), memberId)
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun saveDataToRequest() {
        saveTeamItem.clear()
        /**  获取 projectN 中所有的键 */
        for (i in 0 until tBody.length()) {
            val keysP = projectN.keys()
            val data = tBody[i].toString()
            val saveInfoList: MutableList<SaveGroupParam.SaveTeamItem.SaveInfo> = arrayListOf()
            // 遍历迭代器并输出每个键
            while (keysP.hasNext()) {
                val key = keysP.next()
                saveInfoList.add(
                    SaveGroupParam.SaveTeamItem.SaveInfo(
                        teamId = key.toInt(),
                        value = JSONObject(data).getString(key)
                    )
                )
            }
            saveTeamItem.add(SaveGroupParam.SaveTeamItem(ringId = JSONObject(data).getString("ringId"), saveInfo = saveInfoList))
        }
        saveGroupParam = SaveGroupParam(baseId = baseId, memberId = memberId, saveTeamItem = saveTeamItem)
        LogUtils.debugInfo(Gson().toJson(saveGroupParam).toString())

        showLoading(getString(R.string.loading))
        mViewModel.saveAppTeam(saveGroupParam)
    }
}